package com.changgou.seckill.timer;

import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import entity.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * 定时将秒杀的商品存入到redis缓存
 */
@Component
public class SeckillGoodsPushTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Scheduled(cron = "0/30 * * * * ?")
    public void loadGoodsPusRides(){
        /**
         *   1查出符合条件的
         * 2,秒杀商品库存>0  stock_count
         * 3,审核状态->通过审核 status：1
         * 4，开始时间 start_time   结束时间 end_time
         * 时间菜单的开始时间=<start_time  &&  end_time <= 时间菜单的开始时间+2小时
         */

        //获取时间列表
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date dateMenu : dateMenus) {
            //时间的 字符格式
            String timesSpace = "SeckillGoods_"+DateUtil.data2str(dateMenu,"yyyyMMddHH");

            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            //审核状态 status：1
            criteria.andEqualTo("status","1");
            //秒杀商品库存>0
            criteria.andGreaterThan("stockCount",0);
            //时间菜单的开始时间=<start_time  &&  end_time <= 时间菜单的开始时间+2小时
            criteria.andGreaterThanOrEqualTo("startTime",dateMenu);
            //排除已经存到redis中的seckillgoods 1，求出当前命名空间下所有商品的id（key），2，每次查询排除之前存的商品key数据
            Set keys = redisTemplate.boundHashOps(timesSpace).keys();

            if (keys!= null && keys.size()>0){
                //排除
                criteria.andNotIn("id",keys);
            }
            criteria.andLessThan("endTime",DateUtil.addDateHour(dateMenu,2));
                    //查询数据
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);
            //存入到redis
            for (SeckillGoods seckillGood : seckillGoods) {
                redisTemplate.boundHashOps(timesSpace).put(seckillGood.getId(),seckillGood);
                //商品数据队列储存，防止高并发超卖
                Long[] ids = pushIds(seckillGood.getStockCount(), seckillGood.getId());
                redisTemplate.boundListOps("SeckillGoodsCountList_"+seckillGood.getId()).leftPush(ids);
            }

        }


    }

    /***
     * 将商品id存入数组中
     * @param len  数组长度
     * @param id    商品id
     * @return
     */
    public Long[] pushIds(int len ,Long id){
        Long[] ids = new Long[len];
        for (int i = 0 ; i <ids.length ; i++){
            ids[i] = id;
        }
        return ids;
    }
}
